package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Questionnaire;
import com.itheima.domain.db.Report;
import com.itheima.domain.db.ReportUser;
import com.itheima.domain.db.SoulQuestion;
import com.itheima.service.db.*;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.xml.ws.Response;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bug
 */
@Component
public class TestSoulManager {

    @DubboReference
    private QuestionnaireService questionnaireService;

    @DubboReference
    private ReportUserService reportUserService;

    @DubboReference
    private SoulQuestionService soulQuestionService;

    // 问卷调查
    public ResponseEntity testSoulQuestion() {
        // 获取线程内用户id
        Long userId = UserHolder.get().getId();
        // rpc调用获取问卷信息
        List<Questionnaire> questionnaireList = questionnaireService.findAll();
        // 声明
        List<QuestionnaireVo> voList = new ArrayList<>();
        //        // 遍历
        if (CollectionUtil.isNotEmpty(questionnaireList)) {
            for (Questionnaire questionnaire : questionnaireList) {
                // 创建vo
                QuestionnaireVo vo = new QuestionnaireVo();
                // 查问卷封装问卷信息
                vo.setId(questionnaire.getId().toString());
                vo.setName(questionnaire.getName()); // 问卷名
                vo.setStar(questionnaire.getStar()); // 星级
                vo.setCover(questionnaire.getCover()); // 封面
                vo.setLevel(questionnaire.getLevel()); // 级别
                // 获取问卷id
                Integer questionnaireId = questionnaire.getId();
                // 如果不是初级灵魂题
                if (questionnaireId > 1){
                    // 查询有无次级报告
                    ReportUser report = reportUserService.findReport(userId, questionnaire.getId()-1);
                    // 如过没有次级报告，则上锁
                    if (report == null){
                        vo.setIsLock(1);
                    }
                }

                // 查询问卷试题和选项
                List<SoulQuestionVo> soulQuestionList = soulQuestionService.findByQuestionnaireAndUserId(questionnaireId);
                vo.setQuestions(soulQuestionList);
                // 查询并封装报告id
                ReportUser reportUser = reportUserService.findReport(userId, questionnaireId);
                if (reportUser == null) { // 没有用户报告
                    // 设置用户报告id
                    vo.setReportId(null);
                }else{
                    vo.setReportId(reportUser.getId().toString());
                }

                // 添加到voList
                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private ReportService reportService;

    // 查看结果
    public ResponseEntity report(Integer reportUserId) {
        // 获取线程内用户id
        Long userId = UserHolder.get().getId();
        // 查询用户报告
        ReportUser reportUser = reportUserService.findById(reportUserId);
        // 获取reportUser的report_id
        Integer reportId = reportUser.getReportId();
        if (reportId != null){
            // 查询报告详情
            Report report = reportService.findReportById(reportId);

            // 封装vo
            ReportVo vo = new ReportVo();
            vo.setConclusion(report.getConclusion()); // 结论
            vo.setCover(report.getCover()); // 鉴定图片

            // 4个维度值
            // 声明DimensionsVoList
            List<DimensionsVo> list = new ArrayList<>();

            DimensionsVo dimensionsVo = new DimensionsVo();
            dimensionsVo.setKey(report.getKey1());
            dimensionsVo.setValue(report.getValue1());
            list.add(dimensionsVo);

            dimensionsVo.setKey(report.getKey2());
            dimensionsVo.setValue(report.getValue2());
            list.add(dimensionsVo);

            dimensionsVo.setValue(report.getValue3());
            dimensionsVo.setKey(report.getKey3());
            list.add(dimensionsVo);

            dimensionsVo.setValue(report.getValue4());
            dimensionsVo.setKey(report.getKey4());
            list.add(dimensionsVo);
            vo.setDimensions(list);

            // 查询相似用户封装
            List<ReportUser> similar = reportUserService.findSimilar(reportUser);
            // 声明similarYoVoList
            List<SimilarYouVo> similarYouVoList = new ArrayList<>();
            // 遍历
            if (CollectionUtil.isNotEmpty(similar)) {
                for (ReportUser ru : similar) {
                    // 创建similarYouVo
                    SimilarYouVo similarYouVo = new SimilarYouVo();
                    similarYouVo.setId(ru.getUserId().intValue()); // 用户id
                    similarYouVo.setAvatar(userInfoService.findUserInfoById(ru.getUserId()).getAvatar()); // 用户头像

                    // 封装到vo
                    similarYouVoList.add(similarYouVo);
                }
            }
            vo.setSimilarYou(similarYouVoList);

            return ResponseEntity.ok(vo);
        }else {
            return ResponseEntity.status(500).body("还没答题,请先答题");
        }
    }
    @DubboReference
    private OptionsService optionsService;


    // 提交问卷
    public ResponseEntity commitAnswers(List<Answer> answerList) {
        // 获取线程内的用户id
        Long userId = UserHolder.get().getId();
        // 预定义总分
        Integer total = 0;
        ReportUser reportUser;
        Integer questionnaireId = null;
        // 遍历答案集合
        if (CollectionUtil.isNotEmpty(answerList)) {
            for (Answer answer : answerList) {
                Integer questionId = Integer.parseInt(answer.getQuestionId());
                Integer optionId = Integer.parseInt(answer.getOptionId());
                // 获得选项对应的分数
                Integer score = optionsService.findScore(questionId,optionId);
                // 与总分相加
                total = total + score;
                // 根据试题编号查询问卷编号
                SoulQuestion soulQuestion = soulQuestionService.findQuestionId(questionId);
                // 获取问卷编号
                questionnaireId = soulQuestion.getQuestionType();
            }
        }
        // 根据用户id、问卷id查询report_user
        reportUser = reportUserService.findReport(userId, questionnaireId);
        if (reportUser == null){ // 没有用户报告
            // 新建报告、封装、保存
            reportUser = new ReportUser();
            reportUser.setUserId(userId); // 用户id
            reportUser.setQuestType(questionnaireId); // 问卷id
            reportUser.setTotal(total); // 总分
            reportUserService.save(reportUser);
        }else{
            reportUser.setTotal(total);
        }

        // 根据总分和报告表分值对比
        List<Report> reportList = reportService.findAll();
        if (CollectionUtil.isNotEmpty(reportList)) {
            for (Report report : reportList) {
                Integer score = report.getScore();
                if (total > score){
                    reportUser.setReportId(report.getId());
                }
            }
            // 保存用户报告
            reportUserService.update(reportUser);
        }
        // 查询用户报告
        reportUser = reportUserService.findReport(userId,questionnaireId);
        return ResponseEntity.ok(reportUser.getId().toString());
    }
}
